import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_string_util_lib.dart';

typedef CommonSearchGetContentCallback = String Function();

typedef CommonSearchCustomStyleCallback = Widget Function(Widget textFieldWidget,Widget deleteWidget);

/// 通用搜索栏组件
///
/// @author: zengxiangxi
/// @createTime: 1/6/21 10:37 AM
/// @specialDemand:
class CommonSearchBarWidget extends StatefulWidget {
  ///提示语
  final String hintText;

  ///改变
  final ValueChanged<String> onChanged;

  final ValueChanged<String> onSubmitted;

  final String initContent;

  final CommonSearchCustomStyleCallback customStyleFunc;


  final TextEditingController controller;


  final EdgeInsetsGeometry margin;

  final bool autoFocus;

  final Color bgColor;

  final Color textColor;

  const CommonSearchBarWidget(
      {Key key, this.hintText, this.onChanged, this.onSubmitted,
        this.initContent, this.customStyleFunc, this.controller,
        this.margin, this.autoFocus = false, this.bgColor, this.textColor})
      : super(key: key);

  @override
  CommonSearchBarWidgetState createState() => CommonSearchBarWidgetState();
}

class CommonSearchBarWidgetState extends State<CommonSearchBarWidget> {
  TextEditingController _editingController;

  ValueNotifier<bool> _isShowDeleteValueNotifier;

  FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _editingController = (widget.controller ?? TextEditingController())..text = widget?.initContent;
    _isShowDeleteValueNotifier =
        ValueNotifier(StringUtils.isNotEmpty(_editingController?.text));
    _editingController?.addListener(() {
      if(StringUtils.isNotEmpty(_editingController?.text)){
        _isShowDeleteValueNotifier.value = true;
      }else{
        _isShowDeleteValueNotifier.value = false;
      }
    });

    // _focusNode = FocusNode();
    _focusNode.addListener(() {
      if(StringUtils.isEmpty(_editingController?.text)){
        _isShowDeleteValueNotifier.value = false;
      }else{
        _isShowDeleteValueNotifier.value = true;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _editingController?.clear();
    _editingController?.dispose();
    _isShowDeleteValueNotifier?.dispose();
    _focusNode?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if(widget.customStyleFunc != null){
      return widget.customStyleFunc(_toEditTextWidget(),_toDeleteIcon());
    }
    return Container(
      height: 30,
      margin: widget.margin ?? const EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
          color: widget?.bgColor??ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          borderRadius: BorderRadius.circular(4)),
      child: Row(
        children: <Widget>[
          SizedBox(
            width: 12,
          ),
          Image.asset(
            "images/common_search_ico.png",
            width: 14,
          ),
          SizedBox(
            width: 6,
          ),
          Expanded(
            child: _toEditTextWidget(),
          ),
          _toDeleteIcon(),
        ],
      ),
    );
  }

  Widget _toEditTextWidget() {
    return VgTextField(
      controller: _editingController,
      maxLines: 1,
      maxLength: 20,
      focusNode: _focusNode,
      autofocus: widget?.autoFocus ?? false,
      textInputAction: TextInputAction.search,
      onChanged: widget?.onChanged,
      onSubmitted: widget?.onSubmitted,
      decoration: InputDecoration(
        border: InputBorder.none,
        counterText: "",
        contentPadding: const EdgeInsets.only(bottom:14.5),
        hintText: widget.hintText ?? "",
        hintStyle: TextStyle(
            color: ThemeRepository.getInstance().getTextEditHintColor(),
            fontSize: 13,height: 1.3),
      ),
      style: TextStyle(
          fontSize: 13,
          color: widget?.textColor??ThemeRepository.getInstance().getTextMainColor_D0E0F7(),height: 1.3),
    );
  }

  Widget _toDeleteIcon() {
    return ValueListenableBuilder(
      valueListenable: _isShowDeleteValueNotifier,
      builder: (BuildContext context, bool isShow, Widget child) {
        return AnimatedSwitcher(
          duration: DEFAULT_ANIM_DURATION,
          child: isShow ? child : Container(),
        );
      },
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _editingController?.clear();
          widget?.onSubmitted?.call(_editingController?.text);
          widget?.onChanged?.call(_editingController?.text);
          // VgToolUtils.removeAllFocus(context);
          //延迟1秒
          // Future.delayed(Duration(seconds: 1), () {
          FocusScope.of(context).requestFocus(_focusNode);
          //
          // });
        },
        child: Padding(
          padding: const EdgeInsets.only(left: 8,right: 8,top: 3,bottom: 3),
          child: Container(
            width: 17,
            height: 17,
            decoration: BoxDecoration(
                shape: BoxShape.circle, color: Colors.white.withOpacity(0.1)),
            child: Icon(
              Icons.close,
              size: 11,
              color: ThemeRepository.getInstance()
                  .getTextMainColor_D0E0F7()
                  .withOpacity(0.8),
            ),
          ),
        ),
      ),
    );
  }
}
